#!/usr/bin/env python3
import uuid
import base64
import os
import sys
from PyQt5.QtCore import *
from PyQt5.QtSql import (QSqlDatabase, QSqlQuery, QSqlTableModel)
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import time
import datetime,math
from sjm import sjm_list

class FirstWindow(QWidget):

    close_signal = pyqtSignal()
    def __init__(self, parent=None):
        # super这个用法是调用父类的构造函数
        # parent=None表示默认没有父Widget，如果指定父亲Widget，则调用之
        super(FirstWindow, self).__init__(parent)
        self.resize(250,100)
        self.leName = QLineEdit(self)
        self.leName.setPlaceholderText(u'输入延期天数生成激活码(999关闭任务)')
        self.lePassword = QLineEdit(self)
        #self.lePassword.setEchoMode(QLineEdit.Password)
        self.lePassword.setPlaceholderText(u'输入机器码')
        self.run_day = time.localtime().tm_yday
        self.now_day = time.localtime().tm_yday

        self.pbLogin = QPushButton(u'生成注册码', self)
        self.pbLogin.setFocus()
        self.pbCancel = QPushButton(u'生成激活码', self)
        self.setWindowIcon(QIcon("ico.ico"))
        self.setWindowTitle("WDMSET注册机")
        # self.setWindowFlags( Qt.WindowMaximizeButtonHint|Qt.WindowMinimizeButtonHint| Qt.WindowStaysOnTopHint)
        self.myquery = QSqlQuery()


        self.pbLogin.clicked.connect(self.login)
        self.pbCancel.clicked.connect(self.reject)

        layout = QVBoxLayout()
        layout.addWidget(self.leName)
        layout.addWidget(self.lePassword)


        # 放一个间隔对象美化布局
        spacerItem = QSpacerItem(20, 48, QSizePolicy.Minimum, QSizePolicy.Expanding)
        layout.addItem(spacerItem)

        # 按钮布局
        buttonLayout = QHBoxLayout()
        # 左侧放一个间隔
        spancerItem2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        buttonLayout.addItem(spancerItem2)
        buttonLayout.addWidget(self.pbLogin)
        buttonLayout.addWidget(self.pbCancel)

        layout.addLayout(buttonLayout)

        self.setLayout(layout)

    def removeWarn(self,vid,value):
        print(vid+" 验证码为:"+value)
        try:
            self.myquery.exec_("select count(*) from sjm where sjmm='"+value+"'")
            print(self.myquery.value(0))
            if value in sjm_list:
                print('正确的随机码')
                vsql = "delete  from reference where id='" + vid + "'"
                print(vsql)
                self.myquery.exec_(vsql)
                print(str(self.myquery.value(0)))
                sjm_list.remove(value)
            else:
                print('错误的随机码')

        except ZeroDivisionError as err:  # as 加原因参数名称
            print('Exception: ', err)



    def login(self,fm):
        """返回True或False"""
        input_pw = self.lePassword.text()
        print(input_pw)
        if input_pw != '':
            QInputDialog.getText(self, "注册码", "机器码:"+input_pw+"<br><br>注册码为：", QLineEdit.Normal, encode(input_pw))
        else:
            QMessageBox.about(self, '提醒', "机器码不能为空，请输入")
    def reject(self):
        input_day = self.leName.text()
        sjs = generate_verification_code()
        input_pw = self.lePassword.text()
        print(input_pw)
        print(sjs)
        print(input_day)
        jhm = input_pw+'_'+sjs+'_'+input_day
        print(jhm)
        QInputDialog.getText(self, "激活码", "激活码为：", QLineEdit.Normal, encode(jhm))

    def closeEvent(self, event):
        self.close_signal.emit()
        self.close()



def get_mac_address():
    mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
    mac = ":".join([mac[e:e+2] for e in range(0,11,2)])
    macstr = mac.replace(':', '')
    return macstr

def encode(str):
    bytesString = str.encode(encoding="utf-8")
    #print(bytesString)
    # base64 编码
    encodestr = base64.b64encode(bytesString)
    #print(encodestr)
    print(encodestr.decode())
    return encodestr.decode()

def decode(encode_str):
    decodestr = base64.b64decode(encode_str)
    #print(decodestr.decode())
    return decodestr.decode()

import sqlite3
def getencode():
    try:
        conn = sqlite3.connect('reference.db')
        cursor = conn.cursor()
        sql = '''select sjmm from sjm limit 1'''
        results = cursor.execute(sql)
        one_sjm = results.fetchone()[0]
        sql = "delete from sjm where sjmm = '"+one_sjm+"'"
        print(sql)
        cursor.execute(sql)
        conn.commit()
        return one_sjm
    except ZeroDivisionError as err:  # as 加原因参数名称
            print('Exception: ', err)

import random
def generate_verification_code():
    ''' 随机生成6位的验证码 '''
    code_list = []
    for i in range(10): # 0-9数字
        code_list.append(str(i))
    # for i in range(65, 91): # A-Z
    #     code_list.append(chr(i))
    for i in range(97, 123): # a-z
        code_list.append(chr(i))

    #print(code_list)
    myslice = random.sample(code_list, 6)  # 从list中随机获取6个元素，作为一个片断返回
    verification_code = ''.join(myslice) # list to string
    # print code_list
    # print type(myslice)
    return verification_code

mac = get_mac_address()
encode_str = encode(mac)
print(decode(encode_str))

app = QApplication(sys.argv)
ex = FirstWindow()
ex.show()
sys.exit(app.exec_())